
package com.ceair.mub2c.payment.payments.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ceair.flight.booking.service.IBookingOrderService;
import com.ceair.flight.booking.service.IPromotionService;
import com.ceair.flight.enums.OrderOperateTypeEnum;
import com.ceair.flight.payment.dto.AsyncPaymentCallbackDto;
import com.ceair.flight.payment.dto.CardInfoDto;
import com.ceair.flight.payment.dto.PayResponseDto;
import com.ceair.flight.payment.dto.PayTypeRq;
import com.ceair.flight.payment.dto.SyncPaymentCallbackDto;
import com.ceair.flight.payment.service.IPaymentService;
import com.ceair.flight.po.model.OrderOperateLogDO;
import com.ceair.flight.po.model.PromotionDO;
import com.ceair.flight.po.model.PromotionMemberCouponDO;
import com.ceair.flight.query.dto.EMDOrderDto;
import com.ceair.flight.query.dto.EMDPaxDto;
import com.ceair.flight.query.dto.EMDSegmentDto;
import com.ceair.flight.query.dto.EMDTicketDto;
import com.ceair.flight.query.dto.FlightOrderDto;
import com.ceair.flight.query.dto.PaxDto;
import com.ceair.flight.query.dto.PayDto;
import com.ceair.flight.query.dto.SegmentDto;
import com.ceair.flight.query.dto.TicketDto;
import com.ceair.flight.query.promotion.dto.PromoChannelDto;
import com.ceair.flight.query.promotion.service.IPromoChannelQueryService;
import com.ceair.flight.query.service.IFlightOrderService;
import com.ceair.mub2c.payment.payments.service.PaymentDubboService;
import com.ceair.mub2c.payment.payments.service.PaymentService;
import com.ceair.mub2c.payment.payments.vo.BIG_ORDER;
import com.ceair.mub2c.payment.payments.vo.PASSENGER_INFO;
import com.ceair.mub2c.payment.payments.vo.PayStatusVO;
import com.ceair.mub2c.payment.payments.vo.PaymentVO;
import com.ceair.mub2c.payment.payments.vo.TEAM_NO;
import com.ceair.mub2c.payment.payments.vo.TICKET_INFO;
import com.ceair.mub2c.payment.payments.vo.TRAVEL_INFO;
import com.ceair.unified.businessobject.base.BaseRS;
import com.ceair.unified.businessobject.rqrs.unicfg.UniConfigRQ;
import com.ceair.unified.businessobject.rqrs.unicfg.UniFndConfigListRQ;
import com.ceair.unified.businessobject.rqrs.unicfg.UniFndConfigListRS;
import com.ceair.unified.businessobject.vo.UniFndConfigVO;
import com.ceair.unified.ws.unicfgmanager.IUniConfigManagerWS;

@Service
public class PaymentServiceImpl implements PaymentService {
	
	Logger log = Logger.getLogger(getClass());
	
	private static final String ZERO = "0";
	
	@Autowired
	private PaymentDubboService dubboService;
	
	@Autowired
	private IFlightOrderService flightOrderService;
	
	@Autowired
	private IPromoChannelQueryService promoChannelQueryService;
	
	@Autowired
	private IBookingOrderService bookingOrderService;
	
	@Autowired
	private IPromotionService promotionService;
	
	@Autowired
	private IPaymentService paymentService;
	
	@Autowired
    private IUniConfigManagerWS uniConfigManagerWS;

	@Override
	public PaymentVO paymentSubmit(String sessionId,String sessionUserId,String sessionUserName, String[] productTypes, String orderNo, String[] productIdArray, Integer payType, String bankCode, String accountInfo, BigDecimal amount, BigDecimal pointAmount, String clientIP, String site, CardInfoDto cardInfo, String SCCode, String SubSCCode, String PCCode, String SubPCCode, String PCCodePoint, String SubPCCodePoint, String asyncUrl, String syncUrl, String bookingOrderNo) {	
		log.info("支付提交申请，当前用户sessionID：" + sessionId + " 产品类型：" + productTypes + " 订单号：" + orderNo + " 产品ID：" + productIdArray + " 支付类型：" + payType + " 银行：" + bankCode + " 账户信息：" + accountInfo + " 订单金额：" + amount + " 支付卡号：" + cardInfo.getCardNo() + " 支付卡类型：" + cardInfo.getCardType() + " 站点：" + site + "accountInfo: " + accountInfo);
		String channelCode = getChannelCode(site);
		Integer[] productTypesValue = new Integer[productTypes.length];
		for(int i = 0; i < productTypes.length; i++){
			productTypesValue[i] = Integer.valueOf(productTypes[i]);
		}
		String transWebCountryCode = site.substring(site.length()-2);
		/**监控点开始cd2016-10-31**/
		Date start= new Date();
		SimpleDateFormat ssf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		log.info("ACTION-提交支付请求开始时间="+ssf.format(start)+"--------------------------");		
		Map<String, String> map = dubboService.paymentSubmit(productTypesValue, orderNo, productIdArray, payType, bankCode, 1, accountInfo, amount, pointAmount, sessionUserId, sessionUserName, channelCode, clientIP, cardInfo, SCCode, SubSCCode, PCCode, SubPCCode, PCCodePoint, SubPCCodePoint, sessionId, asyncUrl, syncUrl, transWebCountryCode);
		Date end= new Date();	
		SimpleDateFormat esf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		log.info("ACTION-提交支付请求结束时间="+esf.format(end)+"--------------------------");	
		log.info("ACTION-完成提交支付请求时间="+(end.getTime()-start.getTime())+"毫秒--------------------------");
		/**监控点结束cd**/
		log.info("支付提交申请成功");
		PaymentVO payment = new PaymentVO();
		payment.setParameters(map);
		log.info("增加订单支付操作日志开始");
		try {
			OrderOperateLogDO orderOperateLogDO = new  OrderOperateLogDO(null ==bookingOrderNo? "":bookingOrderNo,//支付需要传入交易单号,前台配合，目前暂时为空
					orderNo,
					OrderOperateTypeEnum.PAYMENT.getCode(),
					"",
					site,
					sessionUserId);
			bookingOrderService.saveOrderOperateLog(orderOperateLogDO);
		}catch (Exception e) {
			log.error("支付操作日志增加失败");
		}
		return payment;
	}
	
	@Override
	public SyncPaymentCallbackDto syncPaymentCallback(String charset, PayResponseDto payResp) {
		log.info("统一支付同步回调地址接收成功");
		return dubboService.syncPaymentCallback(charset, payResp);
	}
	
	@Override
	public AsyncPaymentCallbackDto asyncPaymentCallback(String charset, PayResponseDto payResp) {
		log.info("统一支付异步回调地址接收成功");
		return dubboService.asyncPaymentCallback(charset, payResp);
	}
	
	@Override
	public String getChannelCode(String site) {
		return dubboService.getChannelCode(site).toString();
	}

	@Override
	public BIG_ORDER findFlightOrderList(String orderNO) {
		BIG_ORDER bigOrder = new BIG_ORDER();
		List<FlightOrderDto> orderDtoList = dubboService.getFlightOrderList(orderNO);
		List<TEAM_NO> teamList = new ArrayList<TEAM_NO>();
		for(FlightOrderDto orderDto : orderDtoList){
			TEAM_NO flightVO = new TEAM_NO();
			flightVO.setFLIGHTORDER_CODE(orderDto.getFlightOrderNo());
			flightVO.setPRICE(orderDto.getScNy());
			flightVO.setTAXES(orderDto.getTaxAm());
			flightVO.setFLIGHTORDER_STATUS(orderDto.getOrderSt().toString());
			flightVO.setPAY_SUCCESS_NO(orderDto.getPaySuccessNo());
			List<PASSENGER_INFO> paxList = new ArrayList<PASSENGER_INFO>();
			for(PaxDto pax : orderDto.getPaxs()){
				PASSENGER_INFO paxVO = new PASSENGER_INFO();
				paxVO.setPASSENGER_STATUS(pax.getModifySt().toString());
				paxVO.setEMAIL(pax.getContactEmail());
				paxVO.setPHONE(pax.getContactTel());
				paxVO.setFREQUENT_FLYER(pax.getFfp());
				paxVO.setFIRST_NAME(pax.getPassengerFirstName());
				paxVO.setMIDDLE_NAME(pax.getPassengerMiddleName());
				paxVO.setLAST_NAME(pax.getPassengerLastName());
				paxVO.setTYPE(pax.getPassengerTp());
				paxVO.setIDENTITY_ID(pax.getPassNo());
				List<TRAVEL_INFO> segList = new ArrayList<TRAVEL_INFO>();
				List<TICKET_INFO> tktList = new ArrayList<TICKET_INFO>();
				for(TicketDto ticket : pax.getTicket()){
					TICKET_INFO ticketVO = new TICKET_INFO(ticket.getTktNo(), ticket.getTktSt());
					tktList.add(ticketVO);
				}
				for(SegmentDto segment : pax.getSegments()){
					TRAVEL_INFO segmentVO = new TRAVEL_INFO();
					segmentVO.setDESTINATION(segment.getArrAirpCd());
					segmentVO.setARRIVE_TIME(segment.getArrDt());
					segmentVO.setFARE_CLASS(segment.getCabinClass());
					segmentVO.setFARE_BASIS(segment.getClassTp());
					segmentVO.setORIGIN(segment.getDepAirpCd());
					segmentVO.setDEPARTURE_TIME(segment.getDepDt());
					segmentVO.setFILGH_CODE(segment.getFlightNo());
					segmentVO.setTRAVEL_NUM(segment.getSegId());
					segList.add(segmentVO);
				}
				paxVO.setTRAVEL_INFO_List(segList);
				paxVO.setTICKET_INFO_List(tktList);
				paxList.add(paxVO);
			}
			flightVO.setPASSENGER_INFO_List(paxList);
			teamList.add(flightVO);
		}
		bigOrder.setTEAM_NO_List(teamList);
		return bigOrder;
	}
	

	@Override
	public String findEmdOrder(String emdOrderNO) {
		String s = "";
		List<EMDOrderDto> emdOrderDtoList =  dubboService.getEmdOrder(emdOrderNO);
		if(emdOrderDtoList!=null && emdOrderDtoList.size()>0){
        	EMDOrderDto eMDOrderDto = emdOrderDtoList.get(0);
        	List<EMDPaxDto> eMDOrderDtolist = eMDOrderDto.getEmdPaxDto();
        	if(eMDOrderDtolist!=null && eMDOrderDtolist.size()>0){
        		EMDPaxDto eMDPaxDto = eMDOrderDtolist.get(0);
        		List<EMDSegmentDto> eMDSegmentDtolist = eMDPaxDto.getEmdSegmentDto();
        		if(eMDSegmentDtolist!=null && eMDSegmentDtolist.size()>0){
        			EMDSegmentDto eMDSegmentDto = eMDSegmentDtolist.get(0);
        			List<EMDTicketDto> eMDTicketDtolist = eMDSegmentDto.getEmdTicketDto();
        			if(eMDTicketDtolist!=null && eMDTicketDtolist.size()>0){
        				EMDTicketDto eMDTicketDto = eMDTicketDtolist.get(0);
        				s="{emdTktNo:"+eMDTicketDto.getEmdTktNo()+"}";
        			}
        		}
        	}
        }
		return s;
	}

	@Override
	public PayStatusVO getPayStatus(String orderNo, String[] emdOrderNos,
			String flightOrderNo) {
		PayStatusVO payVO = new PayStatusVO();
		List<PayDto> payDtoList = dubboService.getPayStatus(orderNo, emdOrderNos, flightOrderNo);
		if(payDtoList.size()!=0){
			//根据创建时间排序 为顺序
			sortClass sort = new sortClass();  
	        Collections.sort(payDtoList,sort); 
	        Integer paySt = 0;
	        paySt = payDtoList.get(payDtoList.size()-1).getPaySt();
	        payVO.setPayStatus(paySt);
		}
		return payVO;
	}
	
	
	public class sortClass implements Comparator{  
	    public int compare(Object arg0,Object arg1){  
	    	PayDto payDto0 = (PayDto)arg0;  
	    	PayDto payDto1 = (PayDto)arg1;  
	        int flag = payDto0.getCreateDtm().compareTo(payDto1.getCreateDtm());  
	        return flag;  
	    }  
	}


	@Override
	public boolean validateFlight(FlightOrderDto flightOrderDto) {
		return dubboService.queryAv(flightOrderDto);
		
	}

//	@Override
//	public CommonCardInfoRespDto queryCard(String scCode, String subScCode, String ceairMember) {	
//		return dubboService.queryCard(scCode, subScCode, ceairMember);
//	}
//	
//	@Override
//	public CommonCardInfoRespDto queryCardList(String scCode, String subScCode, String ceairMember) {
//		return dubboService.queryCardList(scCode, subScCode, ceairMember);
//	}
//
//	@Override
//	public CommonCardInfoRespDto insertCard(String scCode, String subScCode, String pcCode, String subPcCode,
//			CardInfoDto cardInfo) {
//		return dubboService.insertCard(scCode, subScCode, pcCode, subPcCode, cardInfo);
//	}
//
//	@Override
//	public CommonCardInfoRespDto deleteCard(String scCode, String subScCode, CardInfoDto cardInfo) {
//		return dubboService.deleteCard(scCode, subScCode, cardInfo);
//	}
	
	@Override
	public List<Map<String, Object>> getPromoPayTypeList(String productOrderNo) {
		List<Map<String,Object>> payTypeList = null;
		try{
			if(productOrderNo.startsWith("11")){
				FlightOrderDto param = new FlightOrderDto();
				param.setFlightOrderNo(productOrderNo);
				List<FlightOrderDto> flightOrderDtoList = flightOrderService.getFlightOrderDOs(param);
				if(null!=flightOrderDtoList&&flightOrderDtoList.size()>0){
					FlightOrderDto flightOrderDto = flightOrderDtoList.get(0);
					if(null!=flightOrderDto && null!=flightOrderDto.getPromoCode() && !"".equals(flightOrderDto.getPromoCode())){
						//使用促销码支付
						List<PromoChannelDto>  promoChannelDtoList  = promoChannelQueryService.getPromoChannelByChannelCode(flightOrderDto.getChannel());
						if(CollectionUtils.isNotEmpty(promoChannelDtoList)){
							payTypeList = new ArrayList<Map<String,Object>>();
							for (PromoChannelDto promoChannelDto : promoChannelDtoList) {
								Map<String,Object> firstChannelMap = new HashMap<String, Object>();
								String payMethod=promoChannelDto.getBankCode();	
								String bankCard=promoChannelDto.getBankCard();	
								List<Map<String, String>> secondChanelList = new ArrayList<Map<String, String>>();
								if(StringUtils.isNotEmpty(bankCard)){
									for(String code:promoChannelDto.getBankCard().split(",")){
										Map<String,String> secondChannelMap = new HashMap<String, String>();
										if("VISA".equals(code)){
											secondChannelMap.put("007", code);
										}
										if("MasterCard".equals(code)){
											secondChannelMap.put("008", code);
										}
										if("Maestro".equals(code)){
											secondChannelMap.put("009", code);
										}
										if("Amex".equals(code)){
											secondChannelMap.put("010", code);
										}
										if("JCB".equals(code)){
											secondChannelMap.put("011", code);
										}
										secondChanelList.add(secondChannelMap);
									}
								}
								firstChannelMap.put(payMethod, secondChanelList);
								payTypeList.add(firstChannelMap);
							}
		
						}
					}
				}
			}
			return payTypeList;
		}catch(Exception e){
			log.error("获取促销码支付方式异常："+productOrderNo,e);
			return null;
		}
	}
	
	@Override
	public List<Map<String, Object>> suspendAndResume(String orderNo, boolean suspend) {
		List<Map<String,Object>> suspendAndResume = dubboService.suspendAndResume(orderNo, suspend);
		return suspendAndResume;
	}

	@Override
	public boolean validatePromotion(List<PromotionDO> promotionDOList,Map<String, Object> param,FlightOrderDto flightOrderDto) {
		boolean flag = false;
		
		int count1 = 0;
		int count2 = 0;
		
		int size = promotionDOList.size();
		
		for(int i = 0; i < size ; i ++){
			PromotionDO promotionDO = promotionDOList.get(i);
			   if (null != promotionDO) {
                   if (!StringUtils.isEmpty(promotionDO.getIsBindMember()) && "1".equals(promotionDO.getIsBindMember())) {
                   	
                       param.put("userId", flightOrderDto.getFfpNo());
                       param.put("promoId", promotionDO.getId().toString());
                       param.put("status", ZERO);
                       PromotionMemberCouponDO promoMemCouDO = promotionService.getMemberCouponIdByCouponId(param);
                       log.info("支付前校验促销码可用状态，绑定且没有可用促销码");
                       if (null == promoMemCouDO) {
                    	   count1 = count1 + 1;
                       }
                   } else {
                       if (null != promotionDO.getPromoNumber() && promotionDO.getPromoNumber() < 0) {
                    	   count2 = count2 + 1;
                       }
                   }
               }
		}
		
		if(count1 < size && count2 < size){
			flag = true;
		}
		
		return flag;
	}

	@Override
	public Map<String,Object> modifyPayType(PayTypeRq payTypeRq) {
		log.info("进去serviceimpl");
		Map<String,Object> map = new HashMap<String,Object>();
		//根据code和type获取原来的支付配置参数  主要是cfgValue
		UniFndConfigListRQ  ucrq =new UniFndConfigListRQ();
		ucrq.setCode("UNI_CHANNEL_PAYCH_CODE");
		ucrq.setCfgType("UNI_CHANNEL");
		UniFndConfigListRS ufc = uniConfigManagerWS.searchUniFndConfigList(ucrq);
		List<UniFndConfigVO> uniFndConfigVOs = ufc.getUniFndConfigVOs();
		UniFndConfigVO ufv = uniFndConfigVOs.get(0);
		String cfgValue = ufv.getCfgValue();
		Map cfgValueMap = JSON.parseObject(cfgValue,Map.class);
		//对cfgValue进行修改
		Set<String> keys = cfgValueMap.keySet();
		boolean channelFlag = false;
		String channel="";
		String channelValue = "";
		for(String key :keys){
			if(key.equals(payTypeRq.getChannel())){
				channelFlag = true;
				channel = key;
				channelValue = cfgValueMap.get(key).toString();
				break;
			}
		}
		boolean payTypeFlag = false;
		String payTypeValue = "";
		if(!channelFlag){
			map.put("success", false);
			map.put("msg", "查不到该渠道号数据");
			return map;
		}else{
			List<Map> list = JSON.parseArray(channelValue, Map.class);
			for (Map object : list) {
				if(object.get("v").equals(payTypeRq.getPayType())){
					payTypeFlag = true;
					if (payTypeRq.getCardType() == null || "".equals(payTypeRq.getCardType())) {
						map.put("success", false);
						map.put("msg", "已存在该支付配置");
						return map;
					}
					if(object.get("s")!=null){
						payTypeValue = object.get("s").toString();
					}
					break;
				}
			}
			
			Map<String,Object> map0 = new HashMap<String,Object>();
			if("VISA".equals(payTypeRq.getCardType())){
				map0.put("t", payTypeRq.getCardType());
				map0.put("v", "007");
			}else if("MasterCard".equals(payTypeRq.getCardType())){
				map0.put("t", payTypeRq.getCardType());
				map0.put("v", "008");
			}else if("Maestro".equals(payTypeRq.getCardType())){
				map0.put("t", payTypeRq.getCardType());
				map0.put("v", "009");
			}else if("Amex".equals(payTypeRq.getCardType())){
				map0.put("t", payTypeRq.getCardType());
				map0.put("v", "010");
			}else if("JCB".equals(payTypeRq.getCardType())){
				map0.put("t", payTypeRq.getCardType());
				map0.put("v", "011");
			}else if(payTypeRq.getCardType() == null || "".equals(payTypeRq.getCardType())){
				
			}else{
				map.put("success", false);
				map.put("msg", "暂不支持该卡种配置");
				return map;
			}
			if(!payTypeFlag){
				//之前没有这个支付类型 需要新增
				Map<String,Object> payeTypeMap = new HashMap<String,Object>();
				payeTypeMap.put("v", payTypeRq.getPayType());
				ArrayList<Map> arrli = new ArrayList<Map>();
				arrli.add(map0);
				payeTypeMap.put("s", arrli);
				list.add(payeTypeMap);
			}else{
				//之前有这个支付类型 需要编辑
				List<Map> list0 = JSON.parseArray(payTypeValue, Map.class);
				for (Map object : list0) {
					if(object.get("t").equals(payTypeRq.getCardType())){
						map.put("success", false);
						map.put("msg", "已存在该卡种配置");
						return map;
					}
				}
				list0.add(map0);
				for (Map object : list) {
					if(object.get("v").equals(payTypeRq.getPayType())){
						object.put("s", list0);
						break;
					}
				}
			}
			cfgValueMap.put(channel, list);
		}
		
		cfgValue = map2Json(cfgValueMap).toString();
		ufv.setCfgValue(cfgValue);
		UniConfigRQ rq =new UniConfigRQ();
		rq.setUniFndConfigVO(ufv);
		rq.setUserId(payTypeRq.getOptID());
		BaseRS ufc1 = uniConfigManagerWS.updateUniConfig(rq);
		if(ufc1.getMsgCode()==1){
			map.put("success", false);
			map.put("msg", "支付配置增加失败");
			return map;
		}
		map.put("success", true);
		map.put("msg", "支付配置增加成功");
		return map;
	}

	@Override
	public Map<String,Object> deletePayType(PayTypeRq payTypeRq) {
		log.info("进去serviceimpl");
		Map<String,Object> map = new HashMap<String,Object>();
		//根据code和type获取原来的支付配置参数  主要是cfgValue
		UniFndConfigListRQ  ucrq =new UniFndConfigListRQ();
		ucrq.setCode("UNI_CHANNEL_PAYCH_CODE");
		ucrq.setCfgType("UNI_CHANNEL");
		UniFndConfigListRS ufc = uniConfigManagerWS.searchUniFndConfigList(ucrq);
		List<UniFndConfigVO> uniFndConfigVOs = ufc.getUniFndConfigVOs();
		UniFndConfigVO ufv = uniFndConfigVOs.get(0);
		String cfgValue = ufv.getCfgValue();
		Map cfgValueMap = JSON.parseObject(cfgValue,Map.class);
		//对cfgValue进行修改
		Set<String> keys = cfgValueMap.keySet();
		boolean channelFlag = false;
		String channel="";
		String channelValue = "";
		for(String key :keys){
			if(key.equals(payTypeRq.getChannel())){
				channelFlag = true;
				channel = key;
				channelValue = cfgValueMap.get(key).toString();
				break;
			}
		}
		boolean payTypeFlag = false;
		String payTypeValue = "";
		if(!channelFlag){
			map.put("success", false);
			map.put("msg", "查不到该渠道号数据");
			return map;
		}else{
			List<Map> list = JSON.parseArray(channelValue, Map.class);
			for (Map object : list) {
				if(object.get("v").equals(payTypeRq.getPayType())){
					payTypeFlag = true;
					payTypeValue = object.get("s").toString();
					break;
				}
			}
			if(!payTypeFlag){
				//之前没有这个支付类型  无法删除
				map.put("success", false);
				map.put("msg", "查不到该支付类型数据");
				return map;
			}else{
				//之前有这个支付类型 需要删除   假如只有一个了 不能删除  卡种为空
				if(list.size() == 1 && (payTypeRq.getCardType() == null || "".equals(payTypeRq.getCardType()))){
					map.put("success", false);
					map.put("msg", "仅剩一个支付类型，无法删除");
					return map;
				}else if(list.size() > 1 && (payTypeRq.getCardType() == null || "".equals(payTypeRq.getCardType()))){
					for (Map object : list) {
						if(object.get("v").equals(payTypeRq.getPayType())){
							list.remove(object);
							break;
						}
					}
				}else if(payTypeRq.getCardType() != null && !"".equals(payTypeRq.getCardType())){
					List<Map> list0 = JSON.parseArray(payTypeValue, Map.class);
					for (Map object : list0) {
						if(object.get("t").equals(payTypeRq.getCardType())){
							//存在该卡种类型
							if(list0.size()==1){
								map.put("success", false);
								map.put("msg", "仅剩一个卡种类型，无法删除");
								return map;
							}else{
								list0.remove(object);
								break;
							}
						}
					}
					for (Map object : list) {
						if(object.get("v").equals(payTypeRq.getPayType())){
							object.put("s", list0);
							break;
						}
					}
				}
			}
			cfgValueMap.put(channel, list);
		}
		
		cfgValue = map2Json(cfgValueMap).toString();
		ufv.setCfgValue(cfgValue);
		UniConfigRQ rq =new UniConfigRQ();
		rq.setUniFndConfigVO(ufv);
		rq.setUserId(payTypeRq.getOptID());
		BaseRS ufc1 = uniConfigManagerWS.updateUniConfig(rq);
		BaseRS bs=uniConfigManagerWS.refreshConfigDataCache();
		if(ufc1.getMsgCode()==1){
			map.put("success", false);
			map.put("msg", "支付配置删除失败");
			return map;
		}
		map.put("success", true);
		map.put("msg", "支付配置删除成功");
		return map;
	}

	public static JSONObject map2Json(Map<String,Object> map){  
        JSONObject json = new JSONObject();  
        Set<String> set = map.keySet();  
        for (Iterator<String> it = set.iterator();it.hasNext();) {  
            String key = it.next();  
            json.put(key, map.get(key));  
        }         
        return json;  
    }
}
